const { firefox } = require('playwright');
const inquirer = require('inquirer')
const chalk = require('chalk')
const { initConfig } = require('./config')
const skipSchool = require('./skipSchool')

module.exports = async (res) => {
  if (res.headless === 'Yes') {
    console.log(chalk.red('请不要操作弹出的浏览器'))
  }
  const browser = await firefox.launch({
    headless: res.headless === 'No',
    // args: [`--window-size=1440,900`]
  });
  const page = await browser.newPage();
  await page.setDefaultTimeout(30000)
  await page.goto('https://www.cugbonline.cn:8443/cas/', {
    waitUntil: 'networkidle',
  });

  // 登录
  console.log('开始登录')
  await page.type('#username', res.username, { delay: 0 })
  await page.type('#password', res.password, { delay: 0 })
  await Promise.all([
    // page.waitForNavigation({
    //   waitUntil: 'domcontentloaded'
    // }),
    page.click('.btn-submit'),
  ]);

  await page.waitForNavigation({
    waitUntil: 'domcontentloaded'
  })

  const frame = page.frames().find((frame) => frame.name() === 'main');
  if (!frame) {
    console.log(chalk.red('登录失败，账号密码错误，请退出重新登录'))
    return process.exit(1)
  }

  const user = await frame.$$eval('.userinfobody li', (element) => {
    const userInfo = {}
    element.forEach((item, index) => {
      userInfo[index] = item.textContent.replace(/\s/g, '').match(/：(\S*)/)?.[1];
    })
    return userInfo
  });

  console.log(chalk.green('登录成功：'))
  console.log('姓名', user[0])
  console.log('在线总时长', user[2])
  console.log('登录次数', user[3])
  console.log()

  let curriculum = await frame.$$eval('.list.clearfix a', (element) => {
    return element.map((item, index) => {
      return {
        name: item.textContent.replace(/\s/g, ''),
        href: item.href
      }
    })
  })
  let className = ''
  if (res.className) { className = res.className }

  if (!className) {
    const res = await inquirer.prompt([{
      name: 'className',
      type: 'list',
      message: '选择刷课的课程？',
      choices: curriculum.map(item => item.name)
    }])
    className = res.className
  }

  // curriculum = [curriculum.find((item,index)=> index === 1)]

  // 保存登录的信息，等下次就不用重新输入了
  initConfig({ ...res, classList: curriculum.map(item => item.name) })

  const selectClass = curriculum.find(item => item.name === className)
  console.log()
  console.log(chalk.green('您的课程及学习时长：'))
  await page.goto(selectClass.href, {
    waitUntil: 'networkidle',
  });
  await page.click('#unitfeedback_score')
  await page.waitForSelector('.fancybox-overlay.fancybox-overlay-fixed')
  await page.waitForTimeout(1000)
  const frame2 = page.frames().find((frame) => {
    return frame.name().includes('fancybox-frame')
  });
  const needstar = await frame2.$$eval('.needstar', (element) => {
    return element[0].textContent.replace(/\s/g, '')
  });
  selectClass.time = Number(needstar)
  if (selectClass.name === "现代远程教育") {
    selectClass.total = 0
  } else {
    selectClass.total = 1200
  }

  const c = selectClass.time >= selectClass.total ? '已' : '未'

  console.log(`课程：${selectClass.name}, 学习时长 ${selectClass.time}/${selectClass.total} ，${c}完成`)
  console.log()
  if (selectClass.time < selectClass.total) {
    console.log()
    let repeatTimes = ''
    if (res.repeatTimes) { repeatTimes = res.repeatTimes }
    if (!repeatTimes) {
      const res = await inquirer.prompt([{
        name: 'repeatTimes',
        type: 'list',
        message: '刷几遍，根据剩余时间酌情选择？',
        choices: [1, 2, 3, 4, 5]
      }])
      repeatTimes = res.repeatTimes
    }
    await skipSchool(repeatTimes, selectClass, page)
    console.log(chalk.green(`您已刷完${repeatTimes}遍所选课程`))
  }
  console.log('没有待处理的任务了，关闭浏览器')
  await browser.close();
  return process.exit(1)
}
